#include <stdio.h>
#include <unistd.h>
#include <math.h>
#include <stdlib.h>

#define NUM 330
FILE *inf, *outf, *comm, *logg;


float correct(int num)
{
    int i,n,t;
    float x,y,z,res;
    for(int i=0; i<10; i++) //мусор
    {
        usleep(30*1000);
        fscanf(comm,"%i %i %f %f",&n, &t, &x, &y);
    };
    for(int i=0; i<num; i++)
    {
        usleep(30*1000);
        fscanf(comm,"%i %i %f %f",&n, &t, &x, &y);
        res=res+pow((x*x+y*y),0.5);
        fprintf(outf,"correction.. %i % \n",100*i/num);
    };
    res=res/(num);
    return res;
}
int main()
{

  int i,j,n,t;


  float data[NUM],dataN[NUM];
  float x,y,xN,yN,z,correction,sq,sum,delta,sigma,acc[NUM],accN[NUM],time[NUM] ;
  char red[80];
  char bufch;
  //запуск цикла
  comm=fopen("/dev/ttyACM0", "w");
  fprintf(comm,"%i \n",1);
  fclose(comm);

  comm=fopen("/dev/ttyACM0", "rt"); //открытие файла каждый раз заново препятствует образованию очереди но теряет данные
  outf= stdout;
  logg=fopen("outf","w");

    //корректрировка

    correction=correct(50);
//    correction=0;
    time[-1]=0;
    fprintf(outf,"Корректрировка завершена. поправка %0.2f по %i значениям\n",correction,100);

    for( i=0; i<NUM-50; i++)
    {
        usleep(30*1000);
        fscanf(comm,"%i %i %f %f",&n, &t, &x, &y );
        data[i]=pow((x*x+y*y),0.5);
//        dataN[i]=pow((xN*xN+yN*yN),0.5);
//       data[i]=x;

        if(x<0){data[i]=(data[i])*(-1);};
 //       data[i]=data[i]-;
        acc[i]=9.8*data[i]/255-9.8*correction/255;

//        if(x<0){dataN[i]=(dataN[i])*(-1);};
//        dataN[i]=dataN[i]-correction;
//        accN[i]=9.8*dataN[i]/255;

        time[i]=time[i-1]+t;
        fprintf(outf,"%i %i %0.0f \n",n,t,data[i]);
 //       fprintf(logg,"%i %i %0.2f %0.2f %0.2f %0.4f \n",n, t, x, y,z, data[i]);
        sprintf(red,"%0.3f %0.6f \n",time[i]/1000,acc[i]); //лог
        for(j=0;j<=100;j++)
        {
            if(red[j]=='.'){red[j]=',';};
        }
        fprintf(logg,"%s",red );
    };
    fprintf(outf," \n");
    fprintf(outf,"------------------------------\n");
    fclose(logg);


    //для логов
/*
    fprintf(logg,"среднее %2.2f \n",av);
    fprintf(logg,"Δ= %2.2f \n",delta);
    fprintf(logg,"σ= %2.2f \n",sigma);
*/

    //лог данных


//  printmass(data,NUM);

  return 0;
}

/*
    //вычисляем среднее\
    sum=0;
    for( i=2; i<=NUM+1; i++)
    {
        sum=sum+ data[i];
        fprintf(outf,"%i \n",data[i]);
    };
    fprintf(outf,"сумма %2.2f \n",sum);
//    fprintf(logg,"сумма %2.2f \n",sum);
    av=sum/float(NUM);

    //вычисление погрености
    sum=0;
    for(i=2;i<=NUM+1;i++)
    {
        sum=sum+pow((data[i]-av),2);
    }
    delta=pow((sum/(NUM*(NUM-1))),0.5);
    sigma=delta/av;

    fprintf(outf,"среднее %2.2f \n",av);
    fprintf(outf,"Δ= %2.2f \n",delta);
    fprintf(outf,"σ= %2.2f \n",sigma);
*/

